<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\ChannelCode\Action\Dashboard\Group;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Plugin\ChannelCode\Contract\ChannelCodeContract;
use MoChat\Plugin\ChannelCode\Contract\ChannelCodeGroupContract;

/**
 * 渠道码删除分组.
 *
 * Class Destroy
 * @Controller
 */
class Destroy extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var ChannelCodeGroupContract
     */
    private $channelCodeGroupService;

    /**
     * @Inject
     * @var ChannelCodeContract
     */
    private $channelCodeService;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class)
     * })
     * @RequestMapping(path="/dashboard/channelCodeGroup/destroy", methods="DELETE")
     */
    public function handle(): array
    {
        // 接收参数
        $params['groupId'] = (int) $this->request->input('groupId');
        // 验证参数
        $this->validated($params);

        if (! empty($this->channelCodeService->getChannelCodesByGroupId($params['groupId']))) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '分组内有渠道活码不允许删除');
        }
        $res = $this->channelCodeGroupService->deleteChannelCodeGroup($params['groupId']);
        if (! is_int($res)) {
            throw new CommonException(ErrorCode::SERVER_ERROR, '移动分组失败');
        }
        return [];
    }

    /**
     * @return string[] 规则
     */
    public function rules(): array
    {
        return [
            'groupId' => 'required',
        ];
    }

    /**
     * 获取已定义验证规则的错误消息.
     */
    public function messages(): array
    {
        return [
            'groupId.required' => '分组id 必传',
        ];
    }
}
